import React, { useState, useEffect,useRef } from "react";
import './index.scss'
import LlxTable from 'components/LlxTable'
import LlxForm from 'components/LlxForm/index'
import { Form ,Button,notification,Select,Divider,Cascader,DatePicker,Tag,Modal,message} from 'antd';
import { connect } from 'react-redux'
import {setPageData,addHistoryRouter,setDictionaries} from 'redux/action'
import { Menu, Dropdown, Space , Tooltip,Image,Alert,Tabs,Input} from 'antd';
import { DownOutlined ,ExclamationCircleOutlined} from '@ant-design/icons'
import {getPublishedBookList,getBookList,editBookStatuss,editBookBatch,saveNewBook,pushPool,getWordList,updateUpperLowerBatchBook} from 'api/index'
import classNames from "classnames";
import UploadPicture from 'components/Upload/index'
import AudioUpload from 'components/Upload/audio'
import UploadJson from 'components/Upload/json'
import {SortableHandle } from 'react-sortable-hoc';
import { MenuOutlined } from '@ant-design/icons';
import PreviewBook from 'components/LlxPreview/book'
import TaskAllocation from "components/Operations/task";
import ChangeStatus from "components/Operations/status";
import AddLabel from "components/Operations/AddLabel";
import DelLabel from "components/Operations/DelLabel";
const DragHandle = SortableHandle(() => <MenuOutlined style={{ cursor: 'grab', color: '#999' }} />);


const { RangePicker } = DatePicker;
const {TabPane} = Tabs
const {Option} = Select
const { SHOW_CHILD } = Cascader;
const { confirm } = Modal;

const AddBook = (props) => {
  const {isModalVisible,setIsModalVisible,dictionaries} = props

  const [form] = Form.useForm();//搜索列表
  const [dataSource,setDataSource] = useState([])
  const [wordOptions,setWordOptions] = useState([])

  const options = wordOptions.map(d => <Option value={d.wordName} key={d.id}>{d.wordName}</Option>);

  const handleSearch = async value => {
    const res = await getWordList({currPage:1,pageSize:20,wordName:value})
    setWordOptions(res.result.records)
  };

  const addForm = [

    {label: '名称',type:'input', name: 'bookName',rules:[
      {
        required: true,
        message: '请输入绘本名称'
      },
    ], span: 6 },
    {label: '标签', name: 'label' , span: 6,render: () => {
    return <Cascader  maxTagCount="responsive" showCheckedStrategy={SHOW_CHILD} fieldNames={{value:'id',label:'labelName'}} options={dictionaries.Label} multiple placeholder="请选择标签" />
     } },
     {label: '适合年纪', name: 'ageId' , span: 6,render: () => {
     return <Select
     allowClear
     optionFilterProp="dictValue"
     showSearch
     fieldNames={{value:'id',label:'dictValue'}}
     placeholder={'请选择适合年纪'}
     options={dictionaries.AgeRange}
   >
   </Select>
     } },
    {label: '主题', name: 'theme' , span: 6,render: () => {
      return <Select
      allowClear
      optionFilterProp="dictValue"
      showSearch
      maxTagCount={1}
      fieldNames={{value:'id',label:'dictValue'}}
      placeholder={'请选择主题'}
      mode="multiple"
      options={dictionaries.Theme}
    >
    </Select>
    } },
    {label: '出版社', name: 'publisher' , span: 6,render: () => {
    return <Select
      allowClear
      optionFilterProp="dictValue"
      showSearch
      fieldNames={{value:'dictValue',label:'dictValue'}}
      placeholder={'请选择类型'}
      options={dictionaries.Publisher}
    >
    </Select>
     } },
    {label: '泛读简介',type:'input', name: 'remark', span: 6 },
    {label: '配音', name: 'dub', span: 6 ,render:()=>{
     return <Select
     allowClear
     optionFilterProp="dictValue"
     showSearch
     maxTagCount={1}
     fieldNames={{value:'id',label:'dictValue'}}
     placeholder={'请选择配音'}
     options={dictionaries.isDub}
   >
   </Select>
    }},
    {label: '字幕类型', name: 'captionPositionId', span: 6 ,rules:[
      {
        required: true,
        message: '请选择字幕类型'
      },
    ],render:()=>{
     return <Select
     allowClear
     optionFilterProp="dictValue"
     showSearch
     maxTagCount={1}
     fieldNames={{value:'id',label:'dictValue'}}
     placeholder={'请选择字幕类型'}
     options={dictionaries.CaptionPosition}
   >
   </Select>
    }},
    {label: '类型', name: 'bookTypeId' , span: 6,render: () => {
      return <Select
     allowClear
     optionFilterProp="dictValue"
     showSearch
     fieldNames={{value:'id',label:'dictValue'}}
     placeholder={'请选择类型'}
     options={dictionaries.BookType}
   >
   </Select>
    } },
    {label: '分享', name: 'share' , span: 6,render: () => {
     return <Select
     allowClear
     optionFilterProp="dictValue"
     showSearch
     fieldNames={{value:'id',label:'dictValue'}}
     placeholder={'请选择系列'}
     options={dictionaries.shareOption}
   >
   </Select>
    } },
    {label: '系列', name: 'serialId' , span: 6,render: () => {
     return <Select
     allowClear
     optionFilterProp="dictValue"
     showSearch
     fieldNames={{value:'id',label:'dictValue'}}
     placeholder={'请选择系列'}
     options={dictionaries.SeriesName}
   >
   </Select>
    } },
    {label: '蓝思值',type:'input', name: 'lexile' , span: 6},
    {label: '级别', name: 'levelId' , span: 6,render: () => {
     return <Select
     allowClear
     optionFilterProp="dictValue"
     showSearch
     fieldNames={{value:'id',label:'dictValue'}}
     placeholder={'请选择级别'}
     options={dictionaries.Level}
   >
   </Select>
    } },
    {label: '核心单词', name: 'coreWords' , span: 6,render: (text,row) => {
     return <Select
     placeholder={'请输入搜索单词'}
     defaultActiveFirstOption={false}
     showArrow={false}
     filterOption={false}
     mode="multiple"
     onSearch={handleSearch}
     notFoundContent={null}
   >
     {options}
   </Select>
    } },
    {label: '阅读模式', name: 'readModeId' , span: 6,render: () => {
     return <Select
     allowClear
     optionFilterProp="dictValue"
     showSearch
     fieldNames={{value:'id',label:'dictValue'}}
     placeholder={'请选择时长'}
     options={dictionaries.ReadMode}
   >
   </Select>
    } },
    {label: '开页方式', name: 'pageId' , span: 6,render: () => {
     return <Select
     allowClear
     optionFilterProp="dictValue"
     showSearch
     fieldNames={{value:'id',label:'dictValue'}}
     placeholder={'请选择开页方式'}
     options={dictionaries.PageType}
   >
   </Select>
    } },
    {label: '书籍封面', name: 'pictureUrl', span: 6,rules:[
      {
        required: true,
        message: '请上传视频封面'
      },
    ],render:()=>{
      return  <UploadPicture pictureUrl={form.getFieldValue().pictureUrl} setPhoto={(value)=>form.setFieldsValue({...form.getFieldValue(),pictureUrl:value})}></UploadPicture>
    }},
  ]

  const columns = [
    {
      title: '排序',
      dataIndex: 'sort',
      width: '10%',
      className: 'drag-visible',
      align: 'center',
      render: () => <DragHandle />,
    },
    {title: '图片', dataIndex: 'pictureUrl',key: 'pictureUrl', align: 'center',render: (text, record) => {
      return <div className="operate_link_group">
        <UploadPicture pictureUrl={record.pictureUrl} setPhoto={(value)=>record.pictureUrl=value}></UploadPicture>
     </div>
    }},
     {title: '音频', dataIndex: 'audioUrl',key: 'audioUrl', align: 'center',render: (text, record) => {
    return <div className="operate_link_group" style={{marginLeft:'10%'}}>
      <AudioUpload audio={record.audioUrl} setAudio={value=>record.audioUrl=value}></AudioUpload>
   </div>
     }},
     {title: '文字', dataIndex: 'content',key: 'content', align: 'center',render: (text, record) => {
     return <div className="operate_link_group">
        <Input defaultValue={record.content} placeholder={'请输入文字'} allowClear onChange={e=>record.content = e.target.value}/>
    </div>
     }}, {title: '字幕', dataIndex: 'captionUrl',key: 'captionUrl', align: 'center',render: (text, record) => {
     return <div className="operate_link_group"  style={{marginLeft:'10%'}}>
      <UploadJson captionUrl={record.captionUrl} setJson={(value)=>record.captionUrl=value}></UploadJson>
    </div>
     }},{title: '编辑', dataIndex: 'active',key: 'active', align: 'center',render: (text, record) => {
    return <div className="operate_link_group">
     <span className="text-link" onClick={()=>removeContent(record.sort)}>移除</span>
   </div>
     }}
    ]

  const onCancel = () => {
    setIsModalVisible(false)
  }

  const onOk = () => {
    form.validateFields().then(async()=>{
      console.log(form.getFieldValue(),dataSource.filter(i=>i.pictureUrl));
      const data = form.getFieldValue()

      data.labels = data.label?data.label.map(i=>{
        return {id:i[1]}
        }):[]
      data.themes = data.theme?data.theme.map(i=>{
        return {id:i}
        }):[]
       
      data.coreWords = data.coreWords?data.coreWords.join(' '):''

      data.bkBookContentFlows=dataSource.filter(i=>i.pictureUrl).map((i,j)=>{
        return {
          sort:j+1,
          audioUrl:i.audioUrl,
          pictureUrl:i.pictureUrl,
          content:i.content,
          captionUrl:i.captionUrl
        }
      })

      const res = await saveNewBook(data)

      message.success('新增成功')

      if(res.result){
        const key = `open${Date.now()}`;


        const value = res.result.replace(/空/g, '空<br/>').split('<br/>').map(i=>{
          return <div>
            {i}
          </div>
        })
  
        notification.open({
          message: '字幕时间为空',
          description:value,
          btn:<Button type="primary" size="small" onClick={() => notification.close(key)}>
          确定
        </Button>,
          key
        });
      }

      setIsModalVisible(false)
     

    }).catch(err=>{
      message.error('新增失败,请检查必填项,或稍后重试');
    })
  }

  const addNewContent = () => {
    setDataSource(value=>[...value,{sort:value.length+1,key:value.length+1+''}])
  }

  const removeContent = (sort) => {
    setDataSource(value=>value.filter(i=>i.sort!==sort))
  }

  const createBarExtraContent = () => {
    return (
     <div>
       <Button type={'primary'} onClick={onOk}>新增</Button>
      </div>
    )
  }

  return <Modal destroyOnClose wrapClassName="modal-full"  visible={isModalVisible} onCancel={onCancel}>
        
  <div className="full-modal-title">
    <Alert message={'新增泛读绘本'} type="success" />
  </div>


  <Tabs defaultActiveKey="1" tabBarExtraContent={createBarExtraContent()}>
    <TabPane tab="基本信息" key="1">
    <LlxForm form={form} labelCol={8} formItem={addForm} />
    </TabPane>
    <TabPane tab="绘本内容" key="2">

      <Button type={'primary'} size={'small'} onClick={addNewContent}>新增</Button>

      <LlxTable
           selectedRowShow={false}
           height={300}
           components={true}
           paginationHide={true}
           setDataSource={setDataSource}
           columns={columns}
           dataSource={dataSource}/>
    </TabPane>
  </Tabs>

</Modal>
}


const formItems = (dictionaries,getUpdateTime,handleSearch,options) => {
  return [
      {label: '名称',type:'input', name: 'bookName', span: 4 },
      {label: '状态', name: 'bookStatus', span: 5 ,render: () => {
      return <Select
      allowClear
      optionFilterProp="dictValue"
      showSearch
      fieldNames={{value:'dictValue',label:'dictValue'}}
      placeholder={'请选择状态'}
      options={dictionaries.wordStatus}
    >
    </Select>
      }},
      {label: '上下架', name: 'shelf', span: 5 ,render: () => {
         return <Select
         allowClear
         optionFilterProp="id"
         showSearch
         fieldNames={{value:'id',label:'dictValue'}}
         placeholder={'请选择上下架状态'}
         options={dictionaries.Publish}
      >
      </Select>
      }},
       {label: '空值', name: 'isNull' , span: 5,render: () => {
      return <Select
      allowClear
      optionFilterProp="dictValue"
      showSearch
      fieldNames={{value:'id',label:'dictValue'}}
      placeholder={'请选择空值'}
      options={dictionaries.BookInfoIsNull}
    >
    </Select>
       }},
      {label: '标签', name: 'label' , span: 5,render: () => {
      return <Cascader  maxTagCount="responsive" showCheckedStrategy={SHOW_CHILD} fieldNames={{value:'id',label:'labelName'}} options={dictionaries.Label} multiple placeholder="请选择标签" />
       } },
       {label: '适合年纪', name: 'ageId' , span: 5,render: () => {
       return <Select
       allowClear
       optionFilterProp="dictValue"
       showSearch
       fieldNames={{value:'id',label:'dictValue'}}
       placeholder={'请选择适合年纪'}
       options={dictionaries.AgeRange}
     >
     </Select>
       } },
      {label: '主题', name: 'theme' , span: 4,render: () => {
        return <Select
        allowClear
        optionFilterProp="dictValue"
        showSearch
        maxTagCount={1}
        fieldNames={{value:'id',label:'dictValue'}}
        placeholder={'请选择主题'}
        mode="multiple"
        options={dictionaries.Theme}
      >
      </Select>
      } },
      {label: '出版社', name: 'publisher' , span: 5,render: () => {
      return <Select
        allowClear
        optionFilterProp="dictValue"
        showSearch
        fieldNames={{value:'dictValue',label:'dictValue'}}
        placeholder={'请选择类型'}
        options={dictionaries.Publisher}
      >
      </Select>
       } },
      {label: '泛读简介',type:'input', name: 'remark', span: 5 },
      {label: '配音', name: 'dub', span: 5 ,render:()=>{
    return <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    maxTagCount={1}
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择配音'}
    options={dictionaries.isDub}
  >
  </Select>
      }},
      {label: '字幕类型', name: 'captionPositionId', span: 5 ,render:()=>{
       return <Select
       allowClear
       optionFilterProp="dictValue"
       showSearch
       maxTagCount={1}
       fieldNames={{value:'id',label:'dictValue'}}
       placeholder={'请选择字幕类型'}
       options={dictionaries.CaptionPosition}
     >
     </Select>
      }},
      {label: '类型', name: 'bookTypeId' , span: 4,render: () => {
        return <Select
       allowClear
       optionFilterProp="dictValue"
       showSearch
       fieldNames={{value:'id',label:'dictValue'}}
       placeholder={'请选择类型'}
       options={dictionaries.BookType}
     >
     </Select>
      } },
      {label: '分享', name: 'share' , span: 5,render: () => {
       return <Select
       allowClear
       optionFilterProp="dictValue"
       showSearch
       fieldNames={{value:'id',label:'dictValue'}}
       placeholder={'请选择系列'}
       options={dictionaries.shareOption}
     >
     </Select>
      } },
      {label: '系列', name: 'serialId' , span: 5,render: () => {
       return <Select
       allowClear
       optionFilterProp="dictValue"
       showSearch
       fieldNames={{value:'id',label:'dictValue'}}
       placeholder={'请选择系列'}
       options={dictionaries.SeriesName}
     >
     </Select>
      } },
      {label: '蓝思值', name: 'lexile' , span: 5,render: () => {
        return <Select
        allowClear
        fieldNames={{value:'id',label:'value'}}
        placeholder={'请选择蓝思值'}
        options={[{id:1,value:'0-100'},{id:2,'value':'100-200'},{id:3,'value':'200-300'},{id:4,'value':'300-400'},{id:5,'value':'400-500'},{id:6,'value':'500-600'},{id:7,'value':'600-700'},{id:8,'value':'700-800'},{id:9,'value':'800-900'},{id:10,'value':'900-1000'},{id:11,'value':'1000-1100'}]}
      >
      </Select>
       } },
      {label: '级别', name: 'levelId' , span: 5,render: () => {
       return <Select
       allowClear
       optionFilterProp="dictValue"
       showSearch
       fieldNames={{value:'id',label:'dictValue'}}
       placeholder={'请选择级别'}
       options={dictionaries.Level}
     >
     </Select>
      } },
      {label: '核心单词', name: 'coreWord' , span: 4,render: () => {
        return <Select
        placeholder={'请输入搜索单词'}
        defaultActiveFirstOption={false}
        showArrow={false}
        filterOption={false}
        mode="multiple"
        onSearch={handleSearch}
        notFoundContent={null}
      >
        {options}
      </Select>
      } },
      {label: '阅读模式', name: 'readModeId' , span: 5,render: () => {
       return <Select
       allowClear
       optionFilterProp="dictValue"
       showSearch
       fieldNames={{value:'id',label:'dictValue'}}
       placeholder={'请选择时长'}
       options={dictionaries.ReadMode}
     >
     </Select>
      } },
      {label: '开页方式', name: 'pageId' , span: 5,render: () => {
       return <Select
       allowClear
       optionFilterProp="dictValue"
       showSearch
       fieldNames={{value:'id',label:'dictValue'}}
       placeholder={'请选择开页方式'}
       options={dictionaries.PageType}
     >
     </Select>
      } },
       {label: '创建人', name: 'createBy',  span: 5 ,render: () => {
         return <Select
         allowClear
         optionFilterProp="userName"
         showSearch
         fieldNames={{value:'userName',label:'userName'}}
         placeholder={'请选择创建人'}
      options={dictionaries.UserSpecies}
    >
    </Select>
      }},
        {label: '负责人', name: 'manager',  span: 5 ,render: () => {
        return <Select
        allowClear
        optionFilterProp="userName"
        showSearch
        fieldNames={{value:'userName',label:'userName'}}
        placeholder={'请选择负责人'}
        options={dictionaries.UserSpecies}
      >
      </Select>
      }},
        {label: '更新人', name: 'updateBy',  span: 4,render: () => {
        return <Select
        allowClear
        optionFilterProp="userName"
        showSearch
        fieldNames={{value:'userName',label:'userName'}}
      placeholder={'请选择更新人'}
      options={dictionaries.UserSpecies}
    >
    </Select>
      }},
       {label: '更新时间', name: 'updateTime', span: 5 ,render: () => {
      return  <RangePicker showTime onChange={getUpdateTime} style={{width:'100%'}}/>
      }}
  ]
}

function BookLibrary(props) {
const {dictionaries} = props
// 数据
const [loading,setLoading] = useState(false) //加载
const [expand,setExpand] = useState(false) //表单伸缩
const [isModalVisiblePreivew,setIsModalVisiblePreivew] = useState(false) //表单伸缩
const [total,setTotal] = useState(0) //总数量
const [id,setId] = useState(0) //id
const [isModalVisible, setIsModalVisible] = useState(false)
const [isModalVisibleTask, setIsModalVisibleTask] = useState(false)
const [isModalVisibleStatus, setIsModalVisibleStatus] = useState(false)
const [isModalVisibleAddLabel, setIsModalVisibleAddLabel] = useState(false)
const [isModalVisibleDelLabel, setIsModalVisibleDelLabel] = useState(false)
const [selectData, setSelectData] = useState([])
const [form] = Form.useForm();//搜索列表

//选择数据
const [selectedRowKeys,setselectedRowKeys] = useState([])
const rowSelection  = useRef({
  selectedRowKeys: selectedRowKeys,
  onChange: value => {
  setselectedRowKeys(value)
  rowSelection.current.selectedRowKeys = value
  }
})

// 7.获取时间
const getUpdateTime = (value,dataString) => {
  const data = form.getFieldValue()
  data.startTime=dataString[0]
  data.endTime=dataString[1]
  form.setFieldsValue(data)
}

const [wordOptions,setWordOptions] = useState([])

const options = wordOptions.map(d => <Option value={d.wordName} key={d.id}>{d.wordName}</Option>);

const handleSearch = async value => {
  const res = await getWordList({currPage:1,pageSize:20,wordName:value})
  setWordOptions(res.result.records)
};
// 表单数据
const formItem = !props.examineStatus?formItems(dictionaries,getUpdateTime,handleSearch,options).filter(i=>!['上下架'].includes(i.label)):formItems(dictionaries,getUpdateTime,handleSearch,options).filter(i=>!['状态','负责人'].includes(i.label))
//分页数据
const [pagination,setPagination] = useState({
  current:1,
  pageSize:20
})
//初始表格数据
const [dataSource,setDataSource] = useState([])
//表头配置信息
const columns = !props.examineStatus?[
      {title: '名称',fixed:'left', dataIndex: 'bookName',width:250, key: 'bookName', align: 'center',render: (text, record) => {
        return <div className="operate_link_group text-nowrap text-link" onClick={()=>goBookInfo(record.id)}>
          {text}
       </div>
     }},
      {title: '状态', dataIndex: 'bookStatus',width:100, key: 'bookStatus', align: 'center'},
      {title: '封面', dataIndex: 'pictureUrl',width:150, key: 'pictureUrl', align: 'center',render:(text)=>{
        return  <div>
          {
            text?<Image
            width={60}
            src={text}
          />:''
          }
        </div>
      }},
      {title: '适合年纪', dataIndex: 'ageName',width:100, key: 'ageName', align: 'center'},
      {title: '主题', dataIndex: 'themes',width:180, key: 'themes', align: 'center', render: (text, record) => {
        return <div className="operate_link_group text-nowrap">
         {record.themes?.map((i,j)=>{
           return   <Tooltip key={i.id} placement="top" title={text.map(i=>i.themeName).join(' ')}>
            {
              j<3?<Tag key={i.id} color="lime">{i.themeName}</Tag>:''
            }
             </Tooltip>
         })}
       </div>}
      },
      {title: '系列', dataIndex: 'serialName',width:150, key: 'serialName', align: 'center'},
      {title: '标签', dataIndex: 'labels', key: 'labels',width:180, align: 'center', render: (text, record) => {
       return <div className="operate_link_group text-nowrap">
        {record.labels?.map((i,j)=>{
          return   <Tooltip key={i.id} placement="top" title={text.map(i=>i.labelName).join(' ')}>
           {
             j<3?<Tag key={i.id} color="green">{i.labelName}</Tag>:''
           }
            </Tooltip>
        })}
      </div>
      }},
      {title: '创建人',width:120, dataIndex: 'createBy', key: 'createBy', align: 'center',render: (text, record) => {
        return <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
          {text}
       </div>
      }},
      {title: '负责人',width:120, dataIndex: 'manager', key: 'manager', align: 'center', render: (text, record) => {
        return <div className={classNames((props.userInfo.user.userName===record.qmanager)||(props.userInfo.user.userName===record.rmanager)?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
        {record.qmanager||record.rmanager}
       </div>
      }},
      {title: '更新人',width:120, dataIndex: 'updateBy', key: 'updateBy', align: 'center',render: (text, record) => {
        return  <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
        {text}
     </div>
      }},
      {title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', align: 'center',width:180},
      {title: '操作',fixed:'right', dataIndex: 'operate', key: 'operate', align: 'center',width:100,render:(text,row)=>{
        return  <div className="text-link" onClick={()=>previewBook(row)}>
         预览
       </div>
      }}
    ]:[
       {title: '名称',fixed:'left', dataIndex: 'bookName',width:250, key: 'bookName', align: 'center',render: (text, record) => {
    return <div className="operate_link_group text-nowrap text-link" onClick={()=>goBookInfo(record.id)}>
      {text}
   </div>
      }},
      {title: '上下架状态', dataIndex: 'upperLowerName', key: 'upperLowerName',width:100, align: 'center', render: (text, record) => {
  return <div className="operate_link_group text-nowrap">
      {
       text==='已上架'?<Tag  color="success">{text}</Tag>:<Tag  color="red">{text}</Tag>
      }
      </div>}},
       {title: '封面', dataIndex: 'pictureUrl',width:150, key: 'pictureUrl', align: 'center',render:(text)=>{
    return  <div>
      {
        text?<Image
        width={60}
        src={text}
      />:''
      }
    </div>
       }},
       {title: '适合年纪', dataIndex: 'ageName',width:100, key: 'ageName', align: 'center'},
       {title: '主题', dataIndex: 'themes',width:180, key: 'themes', align: 'center', render: (text, record) => {
    return <div className="operate_link_group text-nowrap">
     {record.themes?.map((i,j)=>{
       return   <Tooltip key={i.id} placement="top" title={text.map(i=>i.themeName).join(' ')}>
        {
          j<3?<Tag key={i.id} color="lime">{i.themeName}</Tag>:''
        }
         </Tooltip>
     })}
   </div>}
       },
       {title: '系列', dataIndex: 'serialName',width:150, key: 'serialName', align: 'center'},
       {title: '标签', dataIndex: 'labels', key: 'labels',width:180, align: 'center', render: (text, record) => {
   return <div className="operate_link_group text-nowrap">
    {record.labels?.map((i,j)=>{
      return   <Tooltip key={i.id} placement="top" title={text.map(i=>i.labelName).join(' ')}>
       {
         j<3?<Tag key={i.id} color="green">{i.labelName}</Tag>:''
       }
        </Tooltip>
    })}
  </div>
     }},
       {title: '创建人',width:120, dataIndex: 'createBy', key: 'createBy', align: 'center',render: (text, record) => {
    return <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
      {text}
   </div>
      }},
     {title: '更新人',width:120, dataIndex: 'updateBy', key: 'updateBy', align: 'center',render: (text, record) => {
       return  <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
       {text}
     </div>
     }},
     {title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', align: 'center',width:180},
     {title: '操作',fixed:'right', dataIndex: 'operate', key: 'operate', align: 'center',width:100,render:(text,row)=>{
      return  <div className="text-link" onClick={()=>previewBook(row)}>
       预览
     </div>
    }}
    ]
     
     



// 初始化
//1缓存页面数据 缓存表单数据
useEffect(()=>{
  form.setFieldsValue(props.tabList.filter(i=>i.url==='book/bookLibrary')[0]?.data?.form)
  setPagination(props.tabList.filter(i=>i.url==='book/bookLibrary')[0]?.data?.pagination||{
    current:1,
    pageSize:20
  })
  },[]) // eslint-disable-line react-hooks/exhaustive-deps


// 切换发布草稿素材
useEffect(()=>{
  // 获取数据
  getNewList()

  
},[props.examineStatus]) // eslint-disable-line react-hooks/exhaustive-deps

// 方法
// 1.获取数据
const getNewList=(value)=>{
  // 清空选中状态
   setselectedRowKeys(()=>[])
   rowSelection.current.selectedRowKeys=[]

   setLoading(true)

  // 缓存数据
   const data = {
     pagination: value&&value.pageSize?value:pagination,
     form:form.getFieldValue()
  }
    props.setPageDataFn('book/bookLibrary',data) 

    const initialData = async () => {
      const params = JSON.parse(JSON.stringify(form.getFieldValue()))
      params.currPage=value&&value.pageSize?value.current:pagination.current
      params.pageSize=value&&value.pageSize?value.pageSize:pagination.pageSize
      params.labels = params.label?params.label.map(i=>{
        return {id:i[1]}
      }):[]
      params.themes = params.theme?params.theme.map(i=>{
        return {id:i}
      }):[]
      params.coreWords = params.coreWord?params.coreWord.join(' '):''
      if(params.lexile){
        params.startLexile = (params.lexile - 1) * 100
        params.endLexile = params.lexile * 100
        params.lexile=''
      }
     

      if (params.isNull) {
        switch (params.isNull) {
          case 1:
            params.coreWordsIsNull = true
            break
          case 2:
            params.themesIsNull = true
            break
          case 3:
            params.lexileIsNull = true
            break
          case 4:
            params.levelIdIsNull = true
            break
          case 5:
            params.readModeIdIsNull = true
            break
          case 6:
            params.captionPositionIdIsNull = true
            break
          case 7:
            params.pageIdIsNull = true
            break
          case 8:
            params.shareIsNull = true
            break
          default:
            return
        }
      }

      if(!props.examineStatus){
      
        const res = await getBookList(params)
        const data = res.result.records || []

        setDataSource(data)
  
        setTotal(res.result.total)
      } else {
        if (params.shelf === 1) {
          params.upperLower = 1010
        } else if (params.shelf === 2) {
          params.upperLower = 1000
        } else {
          params.upperLower = ''
        }

        const res = await getPublishedBookList(params)
        const data = res.result.records || []
        
        setDataSource(data)
  
        setTotal(res.result.total)
      }
    

      setLoading(false)
    
    }
  
    initialData()
 }
 // 2.重置表单
 const resetForm=()=>{
   form.resetFields()
   setPagination({
    current:1,
    pageSize:20
  })
   getNewList()
 }
//  4.泛读详情
const goBookInfo = (id) => {
props.history.push('/view/book/bookInfo?id=' + id)
props.addRouter({
  menuName:'泛读详情',url:'book/bookInfo?id=' + id 
})
}
//  5.新增泛读
const addNewBook = () => {
  setIsModalVisible(true)
}
//  6.更多操作
const moreOperation = (value) =>{
  // 判断是否选择了数据
  if(!selectedRowKeys.length){
    notification.warning({
      message: '请至少选择一项数据',
      duration:1.5
    });
    return
  }
  
  const data = dataSource.filter((i)=>selectedRowKeys.includes(i.id))

  setSelectData(dataSource.filter((i)=>selectedRowKeys.includes(i.id)))

  switch (value.key) {
    case 'addLabel':
     //  新增标签
     if(data.some(i=>i.bookStatus==='P')){
       notification.warning({
         message: '你的选择中含有已发布的数据，请重新选择',
         duration:1.5
       });
       return
     }
     setIsModalVisibleAddLabel(true)
     break
     case 'delLabel':
       //  删除标签
       if(data.some(i=>i.bookStatus==='P')){
         notification.warning({
           message: '你的选择中含有已发布的数据，请重新选择',
           duration:1.5
         });
         return
       }
       setIsModalVisibleDelLabel(true)
     break
     case 'taskOther':
     //  分配任务
     if(data.some(i=>i.bookStatus==='P')){
       notification.warning({
         message: '你的选择中含有已发布的数据，请重新选择',
         duration:1.5
       });
       return
     }
     setIsModalVisibleTask(true)
     break
     case 'statusCheck':
      //  修改状态
      setIsModalVisibleStatus(true)
     break
     case 'pushTestArea':
       //  添加到测试区
       confirm({
         title: '是否将选中的数据添加到测试区',
         icon: <ExclamationCircleOutlined />,
         onOk() {
          const http = async()=>{
           await pushPool({
             dataId: data.map(i => i.id),
             levelId: 255,
             poolId: 605,
             type: 'BOOK'
           })
 
           notification.success({
             message: '添加成功',
             duration:1.5
           });
             // 清空选中状态
           getNewList()
          }
 
          http()
         },
         onCancel() {
           // 取消
         },
       });
      break
      case 'upperAndLower': 
      // 判断选择的是否同一种数据
      const value = data[0].upperLower
      if (data.filter(i => i.upperLower !== value).length) {
       message.error('请选择同一状态的数据')
       return
     }
      // 上下架操作
      confirm({
       title: '你确定要选择上架或者下架嘛?',
       icon: <ExclamationCircleOutlined />,
       okText: '确定',
       cancelText: '取消',
       async onOk() {
         // 修改数据接口请求
          
         await updateUpperLowerBatchBook({
           ids: data.map(i => i.id),
           upperLower: value === 1010 ? 1000 : 1010
         })
          
         getNewList()
 
         notification.success({
           message: '操作成功',
           description: '操作人：' + props.userInfo.user.userName,
           duration:1
         });
       },
       onCancel() {
       },
     });
     break
    default:
      return
   }

}
// 6.1.更多操作
const menu = (
 <Menu
    onClick={moreOperation}
    items={props.userBtnRole.includes('BOOK_BUTTON_ONE')?[
      {
        label: '新增标签',
        key: 'addLabel',
      },
      {
        label: '移除标签',
        key: 'delLabel',
      },
      {
        label: '任务分配',
        key: 'taskOther',
      },
      {
        label: '状态退回',
        key: 'statusCheck',
      },
      {
        label: '添加至测试区',
        key: 'pushTestArea',
      }
    ]:[
      {
        label: '添加至测试区',
        key: 'pushTestArea',
      }
    ]}
  />
);
// 7.预览
const previewBook = (value) => {
  setId(value.id + '?' + Math.random()*100)
  setIsModalVisiblePreivew(true)
}


return <div className="app-content animate__animated animate__fadeIn">
    {/* 表单 */}
    <LlxForm form={form} formItem={expand?formItem:formItem.filter((i,j)=>j<5)}/>
    {/* 操作按钮 */}
    <div className="operate-btn">
     <div>
       {
          !props.examineStatus ? <Button  onClick={addNewBook} type='primary' className='animate__animated animate__fadeInLeft'>新增</Button>:''
       }
       {
         !props.examineStatus ? <Dropdown overlay={menu}>
         <Button  className='animate__animated animate__fadeInLeft'>
           <Space>
            更多操作
           <DownOutlined />
          </Space>
        </Button>
       </Dropdown>:''
       }
       {
         props.examineStatus ? (
         <>
          <Button  onClick={()=>moreOperation({key:'upperAndLower'})} type='primary' className='animate__animated animate__fadeInLeft'>上下架</Button>
         </>
         ):''
       }
       </div>
       <div>
         <Button  onClick={getNewList} type='primary' className='animate__animated animate__fadeInRight'>查询</Button>
          <Button  type='primary' onClick={resetForm} className='animate__animated animate__fadeInRight'>重置</Button>
          <Button  type='link' onClick={()=>setExpand(i=>!i)} className='animate__animated animate__fadeInRight'>{expand?'收起':'展开'}</Button>
       </div>
    </div>

    <Divider />
    {/* 表格 */}
    <LlxTable
     loading={loading} 
     pagination={pagination}
     setPagination={setPagination}
     selectedRowShow={true}
     rowSelection={rowSelection.current}
     height={!expand?310:550}
     total={total}
     getNewList={getNewList}
     columns={columns}
     dataSource={dataSource}/>

     {/* 弹框 */}
     <PreviewBook id={id}  isModalVisible={isModalVisiblePreivew} setIsModalVisible={setIsModalVisiblePreivew}></PreviewBook>
     {/* 弹框 */}
     <AddBook getNewList={getNewList} dictionaries={dictionaries} userName={props.userInfo.user.userName}  isModalVisible={isModalVisible} setIsModalVisible={setIsModalVisible}></AddBook>
     {/* 任务分配 */}
     <TaskAllocation  editHttp={editBookBatch} type={'BOOK'} statusType={'bookStatus'}  userName={props.userInfo.user.userName} getNewList={getNewList} UserSpecies={dictionaries.UserSpecies} list={selectData} isModalVisible={isModalVisibleTask} setIsModalVisible={setIsModalVisibleTask} ></TaskAllocation>
     {/* 状态变更 */}
     <ChangeStatus http={editBookStatuss} type={'BOOK'} statusType={'bookStatus'}  userName={props.userInfo.user.userName} getNewList={getNewList} labelOption={dictionaries.Label} list={selectData} isModalVisible={isModalVisibleStatus} setIsModalVisible={setIsModalVisibleStatus} ></ChangeStatus>
      {/* 新增标签 */}
      <AddLabel type='BOOK' userName={props.userInfo.user.userName} getNewList={getNewList} labelOption={dictionaries.Label} list={selectData} isModalVisible={isModalVisibleAddLabel} setIsModalVisible={setIsModalVisibleAddLabel} ></AddLabel>
     {/* 移除标签 */}
     <DelLabel type='BOOK' userName={props.userInfo.user.userName} getNewList={getNewList} labelOption={dictionaries.Label} list={selectData} isModalVisible={isModalVisibleDelLabel} setIsModalVisible={setIsModalVisibleDelLabel} ></DelLabel>
  </div>
}

// 映射方法
const mapDispatchToProps = (dispatch) => {
  return {
    addRouter: (route) => dispatch(addHistoryRouter(route)),
    setPageDataFn: (url,data) => dispatch(setPageData(url,data)),
    setDictionaries: (url,data) => dispatch(setDictionaries(url,data))
  }
}

export default connect((state)=>{
  return {userBtnRole:state.userBtnRole,tabList:state.tabList,examineStatus:state.examineStatus,userInfo:state.userInfo,dictionaries:state.dictionaries}
},mapDispatchToProps)(BookLibrary)
